<template>
  <div class="lix-mob__container">
    <div class="lix-mob__phone">
      <input type="text" placeholder="请输入手机号码" placeholder-class="lix-mob__placeholder" @input="phoneNumerInput" />
      <button @click="validateCodeAction" :disabled="isClick">{{ timeBtnData }}</button>
    </div>
    <div class="lix-mob__code">
      <input type="text" placeholder="请输入验证码" placeholder-class="lix-mob__placeholder" @input="validateCodeInput" />
    </div>
    <div class="lix-mob__submit">
      <button @click="submit">确定</button>
    </div>
  </div>
</template>

<script>
import Tip from '../../utils/tips';
import { getSMSCode, bindMobileApi } from '../../api';
let interval = null;

export default {
  props: {
    phoneText: '' // 联系方式
  },
  data() {
    return {
      timeBtnData: '获取验证码',
      isClick: false,
      codeText: '', // 验证码数据
      currentTime: 60
    };
  },
  methods: {
    phoneNumerInput(e) {
      const value = e.mp.detail.value;
      this.phoneText = value;
      console.log(this.phoneText);
    },
    validateCodeInput(e) {
      const value = e.mp.detail.value;
      this.codeText = value;
      console.log(this.codeText);
    },
    validateCodeAction(e) {
      const phoneReg = /^1[3|4|5|6|7|8][0-9]{9}$/;
      if (this.phoneText.length === 0) {
        Tip.error('手机号码不能为空');
        return;
      }

      if (this.phoneText.length !== 11) {
        Tip.error('手机号码长度有误');
        return;
      }

      if (!phoneReg.test(this.phoneText)) {
        Tip.error('不合法的手机号码');
        return;
      }

      // 获取短信验证码接口
      const self = this;
      getSMSCode({
        mobile: this.phoneText,
        scope: 'bind'
      }).then(res => {
        console.log(res);
        // 禁止获取验证码的点击
        self.isClick = true;
        let currentTime = self.currentTime;
        interval = setInterval(function() {
          currentTime -= 1;
          self.timeBtnData = currentTime + '秒后获取';
          if (currentTime <= 0) {
            clearInterval(interval);
            self.timeBtnData = '获取验证码';
            self.currentTime = 60;
            self.isClick = false;
          }
        }, 1000);
      });
    },
    submit(e) {
      if (this.phoneText.length < 10) {
        Tip.error('请输入正确的手机号码');
        console.log(this.phoneText);
        return;
      }
      if (this.codeText.length < 1) {
        Tip.error('请输入短信验证码');
        return;
      }
      bindMobileApi({
        mobile: this.phoneText,
        code: this.codeText
      })
        .then(res => {
          console.log(res);
          Tip.success('绑定成功')
            .then(() => {
              wx.navigateBack();
            });
        });
    }
  }
};
</script>

<style lang="scss">
  @import "../../theme-chalk/bindmobile.scss";
</style>